<html lang="en-US">

<head>
    
<title>问个 Go 问题，字符串 len 为 0 和 字符串为空 ，有啥区别？ - 花落雨忧</title>

<meta property="og:title" content="问个 Go 问题，字符串 len 为 0 和 字符串为空 ，有啥区别？ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
前几天在微信群看到几位大佬在讨论一个问题： ”字符串 len == 0 和 字符串 == &amp;quot;&amp;quot; ，有啥区别？“
这是一个比较小的细节点，同时也勾起了我的好奇心，因此今天这篇文章就和大家一起研究一下他们两者有没有区别，谁的性能更好一些？
[&amp;hellip;] 在测试的方法中，我们分别声明了 Test1 和 Test2 方法：
func Test1() bool &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
前几天在微信群看到几位大佬在讨论一个问题： ”字符串 len == 0 和 字符串 == &amp;quot;&amp;quot; ，有啥区别？“
这是一个比较小的细节点，同时也勾起了我的好奇心，因此今天这篇文章就和大家一起研究一下他们两者有没有区别，谁的性能更好一些？
[&amp;hellip;] 在测试的方法中，我们分别声明了 Test1 和 Test2 方法：
func Test1() bool &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/go-tips-lenstr/">问个 Go 问题，字符串 len 为 0 和 字符串为空 ，有啥区别？</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/04/05</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>前几天在微信群看到几位大佬在讨论一个问题： ”<strong>字符串 len == 0 和 字符串 == &quot;&quot; ，有啥区别</strong>？“</p>
<p>这是一个比较小的细节点，同时也勾起了我的好奇心，因此今天这篇文章就和大家一起研究一下他们两者有没有区别，谁的性能更好一些？</p>
<h2 id="测试方法">测试方法</h2>
<p>在测试的方法中，我们分别声明了 <code>Test1</code> 和 <code>Test2</code> 方法：</p>
<pre tabindex="0"><code>func Test1() bool {
	var v string
	if v == &#34;&#34; {
		return true
	}
	return false
}

func Test2() bool {
	var v string
	if len(v) == 0 {
		return true
	}
	return false
}
</code></pre><p>在方法内部仅做了简单的变量类型声明，分别以 字符串 == &quot;&quot; 和 字符串 len == 0 为判断依据。</p>
<h2 id="测试用例">测试用例</h2>
<p>编写两个方法的 Benchmark，用于后续的性能测试：</p>
<pre tabindex="0"><code>func BenchmarkTest1(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		Test1()
	}
}

func BenchmarkTest2(b *testing.B) {
	for i := 0; i &lt; b.N; i++ {
		Test2()
	}
}
</code></pre><h2 id="结果分析">结果分析</h2>
<pre tabindex="0"><code>$ go test --bench=. -benchmem
goos: darwin
goarch: amd64
BenchmarkTest1-4   	1000000000	         0.305 ns/op	       0 B/op	       0 allocs/op
BenchmarkTest2-4   	1000000000	         0.305 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	_/Users/eddycjy/go-application/awesomeProject/tests	0.688s
</code></pre><p>从多次测试的结果来看，两者比较：</p>
<ul>
<li>性能几乎没有区别，甚至可以出现一模一样的情况。</li>
<li>均不涉及内存申请和操作，均为 0/op。说明变量并不是声明了，就有初始化动作的，这块 Go 编译器有做优化。</li>
</ul>
<p>结果上居然是一样的。根据曹大的提示，我们可以进一步看一下两者的汇编代码，看看具体区别在哪里：</p>
<pre tabindex="0"><code>$ go tool compile -S main.go
&#34;&#34;.main STEXT nosplit size=1 args=0x0 locals=0x0
	0x0000 00000 (main.go:3)	TEXT	&#34;&#34;.main(SB), NOSPLIT|ABIInternal, $0-0
	0x0000 00000 (main.go:3)	FUNCDATA	$0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
	0x0000 00000 (main.go:3)	FUNCDATA	$1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)
	0x0000 00000 (main.go:5)	RET
	0x0000 c3                                               .
go.cuinfo.packagename. SDWARFINFO dupok size=0
	0x0000 6d 61 69 6e                                      main
&#34;&#34;..inittask SNOPTRDATA size=24
	0x0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
	0x0010 00 00 00 00 00 00 00 00                          ........
gclocals·33cdeccccebe80329f1fdbee7f5874cb SRODATA dupok size=8
	0x0000 01 00 00 00 00 00 00 00   
</code></pre><p>无论是 <code>len(v) == 0</code>，又或是 <code>v == &quot;&quot;</code> 的判断，其编译出来的汇编代码都是完全一致的。可以明确 Go 编译器在这块做了明确的优化，大概率是直接比对了。</p>
<p>大家有没有其他的看法和拓展呢，欢迎一起来学习和交流。</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/go-tips-goroutinenums/">Go 群友提问：Goroutine 数量控制在多少合适，会影响 GC 和调度？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/go-typeparams-master/">令人激动！Go 泛型代码合入 master（附尝鲜方法）</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/go-why-path/">意见征集：Go1 要不要移除 GOPATH？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/go1.16-mod/">Go1.16 新特性：Go mod 的后悔药，仅需这一招</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/go1.16-3/">Go1.16 新特性：详解内存管理机制的变更，你需要了解</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/%e9%9d%a2%e8%af%95%e9%a2%98" title="View all posts tagged match">面试题</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/go-tips-goroutinenums/"
                                                    rel="prev">Go 群友提问：Goroutine 数量控制在多少合适，会影响 GC 和调度？</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/go-tips-defer/">Go 群友提问：学习 defer 时很懵逼，这道不会做！</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>